
package com.bangcommunity.bbframe.sdm.aop.wrapper;

import com.bangcommunity.bbframe.common.base.BaseResult;
import com.bangcommunity.bbframe.common.exception.ExceptionUtil;
import com.bangcommunity.bbframe.sdm.aop.WrapAspectUtil;
import com.bangcommunity.bbframe.sdm.aop.WrapException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 *
 * @author tanghc
 * @date 17/1/18
 */
public class CatExceptionAopServiceWrapper extends BaseAopWrapper {

    public CatExceptionAopServiceWrapper(AopWrapper nextWrapper) {
        super(nextWrapper);
    }

    @Override
    protected Object returnWhenException(ProceedingJoinPoint pjp, Exception e) throws Exception {
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        if (WrapAspectUtil.hasAnnotation(pjp.getTarget().getClass(), method, WrapException.class)) {
            if (ExceptionUtil.hasBaseRtmException(method)) {
                throw WrapAspectUtil.exceptionToBaseRtmException(e);
            }
            if (isReturnBaseResult(method)) {
                return WrapAspectUtil.exceptionToBaseResult(e);
            }
        }
        return super.returnWhenException(pjp, e);
    }

    private boolean isReturnBaseResult(Method method) {
        return null != method.getReturnType() && method.getReturnType().equals(BaseResult.class);
    }
}
